<template>
  <div class="app-container org">
    <el-card>
      <el-row>
        <el-col :span="24">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>
      <el-form ref="queryRef" label-width="100" :model="queryParams">
        <el-row>
          <el-col :span="3">
            <el-form-item label="自制样品名称：" prop="sampleName">
              <el-input clearable maxlength="100" placeholder="请输入自制样品名称" v-model="queryParams.sampleName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="唯一性编号：" prop="sampleCode">
              <el-input clearable maxlength="100" placeholder="请输入唯一性编号" v-model="queryParams.sampleCode"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="配置人：" prop="selfAdminId" label-width="65">
              <el-select v-model="queryParams.selfAdminId" clearable filterable>
                <el-option v-for="item in proxy.addListNoLimit(userList, 'userId', 'nickName')" :key="item.userId"
                  :value="item.userId" :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="配置日期：" prop="">
              <el-date-picker value-format="YYYY-MM-DD" type="daterange" v-model="dateRange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测项目：" prop="bucketId" label-width="80">
              <el-select v-model="queryParams.bucketId" clearable filterable remote reserve-keyword remote-show-suffix
                :remote-method="remoteMethod" :loading="loading" style="width: 100%">
                <el-option v-for="item in jcxmList" :key="item.bucketId" :value="item.bucketId" :label="item.jcxmName">
                  <span v-html="transformation(item.jcxmName)"></span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="检测项目类型：" prop="isSingle">
              <el-select placeholder="请选择" clearable v-model="queryParams.isSingle" @keyup.enter="handleQuery" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_bzwz_jcxm_type)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" style="padding-left: 30px;">
            <el-row>
              <el-radio label="0" v-model="queryParams.isLike">模糊搜索</el-radio>
              <el-radio label="1" v-model="queryParams.isLike">精准搜索</el-radio>
            </el-row>
          </el-col>
          <el-col :span="2">
            <el-row>
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">自制样品列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px;">
          <el-button type="success" link icon="Plus" @click="batchUse">批量领用</el-button>
        </el-row>
        <el-table ref="mainTableRef" :data="useTable" @selection-change="handleSelChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="唯一性编号" prop="sampleCode" align="center" />
          <el-table-column label="自制样品名称" prop="sampleName" align="center" />
          <el-table-column label="种类" prop="sampleType" align="center">
            <template #default="scope">
              <dict-tag :options="sys_self_sample_type" :value="scope.row.sampleType" />
            </template>
          </el-table-column>
          <el-table-column label="溶剂" prop="rj" align="center">
          </el-table-column>
          <el-table-column label="定容体积" prop="drtj" align="center">
            <template #default="scope">
              <span v-html="scope.row.drtj +
                transformation(scope.row.drtjUnitName)
                "></span>
            </template>
          </el-table-column>
          <el-table-column label="配置日期" prop="createDate" align="center" />
          <el-table-column label="有效日期" prop="yxDate" align="center" />
          <el-table-column label="保存条件" prop="saveCondition" align="center" />
          <el-table-column label="保存位置" prop="saveLocation" align="center" />
          <el-table-column label="配置人" prop="selfAdminId" align="center">
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  userList,
                  "userId",
                  scope.row.selfAdminId,
                  "nickName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="检测项目数" prop="jcxmCount" align="center">
            <template #default="scope">
              <el-button link @click="jcxmCountClick(scope.row.sampleId)">{{
                scope.row.jcxmName ? scope.row.jcxmName : scope.row.jcxmCount
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="余量" prop="remainDrtj" align="center" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="useZzyp(scope.row.sampleId)">领用</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </el-card>
    <!-- 点击详情弹窗 -->
    <!-- 点击行内检测项目数的弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="jcxmOpen" @close="closedHnDialog" :title="title">
      <el-row>
        <p class="pinformation">检测项目列表</p>
        <p class="totalStyle">共 {{ hnTable.length }} 条数据</p>
      </el-row>
      <el-table :data="hnTable">
        <el-table-column label="检测项目" prop="bucketId" align="center">
          <template #default="scope">
            <span v-html="transformation(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="浓度值" prop="con" align="center" />
        <el-table-column label="浓度值单位" prop="conUnit" align="center">
          <template #default="scope">
            <span v-html="transformation(scope.row.conUnitName)"></span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="jcxmOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 点击领用弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="useOpen" @close="closedDialog" :title="useTitle" width="1600">
      <el-row>
        <p class="pinformation">领用列表</p>
        <p class="totalStyle">共 {{ multiplexTable.length }} 条数据</p>
      </el-row>
      <el-table :data="multiplexTable">
        <el-table-column label="唯一性编号" prop="sampleCode" align="center" />
        <el-table-column label="自制样品名称" prop="sampleName" align="center" />
        <el-table-column label="种类" prop="sampleType" align="center">
          <template #default="scope">
            <dict-tag :options="sys_self_sample_type" :value="scope.row.sampleType" />
          </template>
        </el-table-column>
        <el-table-column label="溶剂" prop="rj" align="center">
        </el-table-column>
        <el-table-column label="定容体积" prop="drtj" align="center">
          <template #default="scope">
            <span v-html="scope.row.drtj + transformation(scope.row.drtjUnitName)
              "></span>
          </template>
        </el-table-column>
        <el-table-column label="配置日期" prop="createDate" align="center" />
        <el-table-column label="有效日期" prop="yxDate" align="center" />
        <el-table-column label="保存条件" prop="saveCondition" align="center" />
        <el-table-column label="保存位置" prop="saveLocation" align="center" />
        <el-table-column label="配置人" prop="selfAdminId" align="center">
          <template #default="scope">
            {{
              proxy.getItemByArray(
                userList,
                "userId",
                scope.row.selfAdminId,
                "nickName"
              )
            }}
          </template>
        </el-table-column>
        <el-table-column label="检测项目数" prop="jcxmCount" align="center">
          <template #default="scope">
            <el-button link @click="jcxmCountClick(scope.row.sampleId)">{{
              scope.row.jcxmName ? scope.row.jcxmName : scope.row.jcxmCount
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 20px">
        <el-col :span="4" v-if="!lyForm.isDisplay">
          <el-form-item label="领用方式：">
            <el-radio-group v-model="lyForm.outType" @change="outTypeChange">
              <el-radio :label="0">整个领用</el-radio>
              <el-radio :label="1">分装领用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="lyForm.isDisplay">
          <el-form-item label="领用方式："> 整个领用 </el-form-item>
        </el-col>
        <el-col :span="2" style="padding-left: 10px" v-if="!lyForm.isDisplay">
          <el-form-item label="领用次数：" prop="">
            {{ lyForm.outCount }}
          </el-form-item>
        </el-col>
        <el-col :span="3" v-if="!lyForm.isDisplay">
          <el-form-item label="库存量：" prop="drtj">
            {{ lyForm.drtj
            }}<span v-html="transformation(lyForm.drtjUnitName)" />
          </el-form-item>
        </el-col>
        <el-col :span="5" v-if="!lyForm.isDisplay">
          <el-form-item label="领用量：" prop="outGg">
            <el-col :span="16">
              <el-input clearable maxlength="100" :disabled="!lyForm.outType" v-model="lyForm.outGg"
                @input="outGgChange"></el-input>
            </el-col>
            <el-col :span="4" style="padding-left: 10px">
              <span v-html="transformation(lyForm.drtjUnitName)" />
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="3" v-if="!lyForm.isDisplay">
          <el-form-item label="剩余量：" prop="saveLocation">
            {{ lyForm.remainDrtj
            }}<span v-html="transformation(lyForm.drtjUnitName)" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="领用日期：" prop="saveLocation">
            <el-date-picker v-model="lyForm.outDate" placeholder="请选择领用日期" type="date" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-row justify="end">
            <el-button type="success" @click="saveLy">确 定</el-button>
            <el-button type="danger" @click="useOpen = false">取 消</el-button>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="BzwzOutin">
import {
  newListLedger,
  sampleList,
  zzypViewForm,
  bzwzOut,
  batchBzwzOut,
  getJcxmList,
  getBzwzList,
} from "@/api/resource/selfSampleLedger";
import { getCurrentTime } from "@/api/common";
import { listUser } from "@/api/contract/check";
import { getUnitList } from "@/api/store/unit";

const { proxy } = getCurrentInstance();
const {
  sys_self_sample_type,
  sys_bzwz_gslb,
  sys_bzwz_gqlx,
  sys_bzwz_jcxm_type,
} = proxy.useDict(
  "sys_self_sample_type",
  "sys_bzwz_gslb",
  "sys_bzwz_gqlx",
  "sys_bzwz_jcxm_type"
);

const useTable = ref([]);
const multiplexTable = ref([]);
const jcxmList = ref([]);
const title = ref("查看检测项目");
const jcxmOpen = ref(false);
const useOpen = ref(false);
const useTitle = ref("自制样品领用");
const dateRange = ref([]);
const data = reactive({
  form: { selfSampleBzwzList: [], selfSampleJcxmList: [] },
  queryParams: {
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页数据条数
    isLike: "0",
    selfAdminId: -1,
    isSingle: -1
  },
  rules: {
    // bzwzCode: [
    //   { required: true, message: "唯一性编号不能为空", trigger: "blur" },
    // ],
    // bzwzName: [
    //   { required: true, message: "标准物质名称不能为空", trigger: "blur" },
    // ],
    // bzwzType: [{ required: true, message: "种类不能为空", trigger: "blur" }],
    // totalGg: [{ required: true, message: "规格数量不能为空", trigger: "blur" }],
    // ggUnit: [{ required: true, message: "规格单位不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

const bzwzList = ref([]);
getBzwzList().then((res) => {
  bzwzList.value = res.data;
});
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const total = ref(0);
function getList() {
  newListLedger(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      useTable.value = res.rows;
      total.value = res.total;
    }
  );
}
getList();

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

const hnTable = ref([]);
function jcxmCountClick(row) {
  sampleList({ sampleId: row }).then((res) => {
    hnTable.value = res.data;
    jcxmOpen.value = true;
  });
}

function closedDialog() {
  multiplexTable.value = [];
  count.value = 0;
}

const unitList = ref([]);
getUnitList({ unitGroup: 0 }).then((res) => {
  getUnitList({ unitGroup: 5 }).then((res1) => {
    unitList.value = Object.assign(res1.data, res.data);
  });
});

const lyForm = ref({});

function batchUse() {
  lyForm.value.isDisplay = true;
  getCurrentTime().then((res) => {
    lyForm.value.outDate = res.data;
  });
  useOpen.value = true;
}

function useZzyp(id) {
  zzypViewForm(id).then((res) => {
    multiplexTable.value = [res.data];
    lyForm.value = res.data;
    lyForm.value.outType = 0;
    if (!lyForm.value.outCount) lyForm.value.outCount = 0;
    getCurrentTime().then((res) => {
      lyForm.value.outDate = res.data;
    });
    // lyForm.value.outDate =
    //   new Date().getFullYear() +
    //   "-" +
    //   ("0" + (new Date().getMonth() + 1)).substr(-2) +
    //   "-" +
    //   ("0" + new Date().getDate()).substr(-2);
    useOpen.value = true;
  });
}

function saveLy() {
  if (lyForm.value.isDisplay) {
    lyForm.value.sampleIds = multiplexTable.value.map((item) => {
      return item.sampleId;
    });
    batchBzwzOut(lyForm.value).then((res) => {
      proxy.$modal.msgSuccess("批量领用成功");
      useOpen.value = false;
      getList();
    });
  } else {
    if (lyForm.value.outType === 1) {
      if (lyForm.value.outGg !== "0" && lyForm.value.outGg) {
        bzwzOut(lyForm.value).then((res) => {
          proxy.$modal.msgSuccess("领用成功");
          useOpen.value = false;
          getList();
        });
      } else {
        proxy.$modal.msgError("领用量不能为0或空");
      }
    } else {
      bzwzOut(lyForm.value).then((res) => {
        proxy.$modal.msgSuccess("整个领用成功");
        useOpen.value = false;
        getList();
      });
    }
  }
}

const count = ref(0);
function outGgChange() {
  if (lyForm.value.outGg) {
    if (count.value === 0) {
      count.value = lyForm.value.remainDrtj;
    }
    if (lyForm.value.outGg > count.value) {
      lyForm.value.outGg = count.value;
      lyForm.value.remainDrtj = 0;
    } else {
      lyForm.value.remainDrtj = count.value - lyForm.value.outGg;
    }
  } else {
    if (count.value !== 0) {
      lyForm.value.remainDrtj = count.value;
    }
  }
}

function outTypeChange() {
  if (!lyForm.value.outType) {
    lyForm.value.outGg = "";
    outGgChange();
  }
}

function handleSelChange(selection) {
  multiplexTable.value = selection;
}

getJcxmList().then((res) => {
  jcxmList.value = res.data;
});

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

function transformation(row) {
  const a = proxy.getSupAndSub(row);
  return a;
}

function closedHnDialog() {
  hnTable.value = [];
}

const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
});

const loading = ref(false);

function remoteMethod(val) {
  if (val) {
    loading.value = true;
    setTimeout(() => {
      getJcxmList({ jcxmName: val }).then((res) => {
        loading.value = false;
        jcxmList.value = res.rows;
      });
    }, 200);
  } else {
    jcxmList.value = [];
  }
}
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 5px;
}
</style>
